<template>
  <div class="app-container">
    <v-row :gutter="20">
      <v-col>
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="岗位编码"
                v-model="queryParams.postCode"
                placeholder="请输入岗位编码"
                outlined
                dense
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 240px;"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="岗位名称"
                v-model="queryParams.postName"
                placeholder="请输入岗位名称"
                outlined
                dense
                style="width: 240px;"
                @keyup.enter.native="handleQuery"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px;max-width: 150px">
              <v-select
                label="状态"
                v-model="queryParams.status"
                :items="statusOptions"
                item-text="dictLabel"
                item-value="dictValue"
                dense
                outlined
                clearable
                style="width: 130px;"
              ></v-select>
            </v-col>
            <!-- 按钮区-->
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 0;margin-left: 1rem;height: 40px;margin-top: 8px">
              <p style="display: inline-block;position: absolute">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>

        <!-- 表格操作按钮区 -->
        <v-row style="margin-bottom: -5px">
          <v-col md="1" style="max-width: 84px">
            <v-btn
              color="primary"
              plain
              small
              outlined
              @click="handleAdd"
              v-hasPermi="['system:post:add']">
              <v-icon left>
                mdi-plus
              </v-icon>
              新增
            </v-btn>
          </v-col>
          <v-col md="1" style="max-width: 84px">
            <v-btn
              small
              plain
              outlined
              :disabled="single"
              @click="handleUpdate(ids[0])"
              v-hasPermi="['system:post:edit']">
              <v-icon left>
                mdi-pencil
              </v-icon>
              修改
            </v-btn>
          </v-col>
          <!--todo 二次确认删除按钮 -->
          <v-col md="1" style="max-width: 84px">
            <v-btn
              small color="error"
              plain
              outlined
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:post:remove']">
              <v-icon left>
                mdi-delete
              </v-icon>
              删除
            </v-btn>
          </v-col>
          <v-col md="1" style="max-width: 84px">
            <v-btn
              type="warning"
              small
              plain
              outlined
              @click="handleExport"
              v-hasPermi="['system:post:export']">
              <v-icon left>
                mdi-upload
              </v-icon>
              导出
            </v-btn>
          </v-col>
          <v-col style="float: right">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </v-col>
        </v-row>
      </v-col>
    </v-row>
    <v-main>
      <v-data-table v-if="postList"
                    v-model="ids"
                    :headers="headers"
                    :items="postList"
                    :items-per-page="queryParams.pageSize"
                    hide-default-footer
                    :loading="loading"
                    loading-text="加载中,请稍后.."
                    show-select
                    item-key="postId"
                    class="elevation-1"
                    no-data-text="暂无数据"
      >
        <!-- 状态插槽 -->
        <template v-slot:item.status="{ item }">
          <div v-if="item.status === '1'">正常</div>
          <div v-if="item.status === '0'" style="color: red">停用</div>
        </template>

        <!-- 按钮插槽 -->
        <template v-slot:item.actions="{ item }">
          <v-btn text
                 small
                 plain
                 height="20"
                 width="40"
                 @click="handleUpdate(item)"
                 v-hasPermi="['system:user:edit']">
            <v-icon small>
              mdi-pencil
            </v-icon>
            修改
          </v-btn>
          <!-- 删除确认 -->
          <span v-if="item && item.showConfirmDelete">
                <v-tooltip top>
                  <template v-slot:activator="{ on, attrs }">
                    <v-btn
                      small color="error"
                      plain
                      height="20"
                      width="40"
                      v-bind="attrs"
                      v-on="on"
                      @click="handleDelete(item)"
                      v-hasPermi="['system:user:remove']">
                      <v-icon small>
                        mdi-delete
                      </v-icon>
                      确定
                    </v-btn>
                  </template>
                  <span>请再次点击确定删除</span>
                </v-tooltip>
              </span>
          <span v-if="item && !item.showConfirmDelete">
                <v-btn color="#C62828"
                       small
                       plain
                       height="20"
                       width="40"
                       @click="onClickDelete(item)">
                  <v-icon small>
                    mdi-delete
                  </v-icon>
                  删除
                </v-btn>
              </span>
          <!-- todo 重置密码按钮 -->
        </template>
      </v-data-table>
      <!-- 外部分页-->
      <div class="d-flex align-center justify-end text-center">
        <div class="d-flex" style="margin-top: 3px;font-size: 14px;font-weight: 400">
          <span>每页</span>
          <v-select
            v-model="queryParams.pageSize"
            :items="numbers"
            dense
            @change="getList" style="max-width: 80px;max-height: 20px;margin-top: -4px;text-align: center;">
            <template v-slot:selection="{ item, index }">
                  <span style="width: 100%">
                    {{ item }}
                  </span>
            </template>
          </v-select>
          <span>条记录</span>
        </div>
        <v-pagination
          v-model="queryParams.pageNum"
          @input="getList"
          :length="queryParams.totalPages"
          :total-visible="7"
        ></v-pagination>
      </div>
    </v-main>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange" v-if="false">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="岗位编号" align="center" prop="postId" />
      <el-table-column label="岗位编码" align="center" prop="postCode" />
      <el-table-column label="岗位名称" align="center" prop="postName" />
      <el-table-column label="岗位排序" align="center" prop="postSort" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="岗位名称" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="岗位编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入编码名称" />
        </el-form-item>
        <el-form-item label="岗位顺序" prop="postSort">
          <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增岗位 -->
    <post-add ref="addPostFormRef" :visible="showAddPost" @done="handleQuery" @updateVisible="updateVisible" :statusOptions="statusOptions"></post-add>
    <!-- 修改岗位 -->
    <post-edit ref="addEditFormRef" :visible="showEditPost" @done="handleQuery" @updateVisible="updateVisible" :data="form"
               :statusOptions="statusOptions"></post-edit>
  </div>
</template>

<script>
import { listPost, getPost, delPost, addPost, updatePost } from "@/api/system/post";
import PostAdd from "./postAdd";
import PostEdit from "./postEdit";

export default {
  name: "Post",
  components: {
    PostAdd,
    PostEdit
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined,
        totalPages: 0, // 总页数
      },
      showAddPost: false,
      showEditPost: false,
      // 表单参数
      form: {},
      // v-table 表格头
      headers: [
        { text: '岗位编号', value: 'postId', align: 'center' },
        { text: '岗位编码', value: 'postCode', align: 'center' },
        { text: '岗位名称', value: 'postName', align: 'center' },
        { text: '岗位排序', value: 'postSort', sortable: false, align: 'center' },
        { text: '状态', value: 'status', sortable: false, align: 'center' },
        { text: '创建时间', value: 'createTime', sortable: true, align: 'center' },
        { text: '操作', value: 'actions', sortable: true, align: 'center' },
      ],
      // 列信息
      columns: [
        //{ key: 0, label: `岗位编号`, visible: true },
        //{ key: 1, label: `岗位编码`, visible: true },
        //{ key: 2, label: `岗位名称`, visible: true },
        //{ key: 3, label: `岗位排序`, visible: true },
        //{ key: 5, label: `状态`, visible: true },
        //{ key: 6, label: `创建时间`, visible: true }
      ],
      numbers: [10, 15, 20, 50, 100], // 每页条数选择
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" }
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" }
        ],
        postSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    ids() {
      this.handleSelectionChange();
    }
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.ids = [];
      this.loading = true;
      listPost(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        // 总页数
        this.queryParams.totalPages = Math.ceil(this.total / this.queryParams.pageSize);
        this.loading = false;
      });
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //this.resetForm("queryForm");
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      //this.ids = selection.map(item => item.postId)
      //this.single = selection.length!=1
      //this.multiple = !selection.length
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.showAddPost = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const postId = row.postId || this.ids
      getPost(postId).then(response => {
        this.form = Object.assign(response.data);
        this.showEditPost = true;
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.postId != undefined) {
            updatePost(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete(item) {
      this.$set(item, 'showConfirmDelete', true);
      setTimeout(() => {
        this.$set(item, 'showConfirmDelete', false);
      }, 3500);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      const postIds = row.postId || this.ids.map(item => item.postId);
      await delPost(postIds).then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '删除成功',
            color: 'success'
          })
          this.getList();
        }
      });
    },
    updateVisible(value) {
      this.showAddPost = value;
      this.showEditPost = value;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
